import { createI18n } from 'vue-i18n'
import zhCN from './zh-cn'
import enUS from './en-us'

// 支持的语言列表
export const SUPPORTED_LANGUAGES = {
  'zh-cn': {
    name: '中文',
    locale: 'zh-cn'
  },
  'en-us': {
    name: 'English',
    locale: 'en-us'
  }
}

// 默认语言
const DEFAULT_LOCALE = 'zh-cn'

// 获取保存的语言偏好
const getSavedLocale = (): string => {
  const saved = localStorage.getItem('app-language')
  return saved && Object.keys(SUPPORTED_LANGUAGES).includes(saved) ? saved : DEFAULT_LOCALE
}

// 消息资源
export const messages = {
  'zh-cn': zhCN,
  'en-us': enUS
}

// 创建i18n实例
const i18n = createI18n({
  legacy: false,
  locale: getSavedLocale(),
  fallbackLocale: DEFAULT_LOCALE,
  messages,
  globalInjection: true
})

// 导出i18n实例和工具函数
export const { t, locale } = i18n.global

// 切换语言
export const switchLanguage = (newLocale: string): void => {
  if (Object.keys(SUPPORTED_LANGUAGES).includes(newLocale)) {
    locale.value = newLocale
    localStorage.setItem('app-language', newLocale)
  }
}

export default i18n